<template>
	<view>
		<view class="ipt-box">
			<input @input="inputs" class="ipt" :value="search_val" type="text" placeholder="请输入关键词搜索歌手或歌曲...">
			<view @click="goSearchDetail" class="search-btn">
				搜索
			</view>
		</view>
		<view class="suggest">
			<view @click="suggestClick(item)" class="list" v-for="item,index in suggest_list" :key="index">
				<image src="../../static/search.png"></image>
				<view>{{item.keyword}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getSearchSuggestApi,
		getSearchDefaultApi
	} from "@/api/api.js"
	export default {
		data() {
			return {
				search_val: '',
				suggest_list: []
			}
		},
		watch: {
			search_val(val) {
				if (!val) this.suggest_list = [];
			}
		},
		onLoad() {
			this.getSearchDefault();
		},
		methods: {
			async getSearchDefault() {
				let res = await getSearchDefaultApi();
				let defaultWords = res.data;
				defaultWords.map(it => {
					this.$set(it, 'keyword', it.searchWord);
				});
				this.suggest_list = defaultWords.splice(0, 10);
			},
			async inputs(e) {
				this.search_val = e.detail.value;
				if (this.search_val) {
					this.suggest_list = [];
					let data = {
						keywords: this.search_val
					};
					let res = await getSearchSuggestApi(data);
					this.suggest_list = res.result.allMatch;
				} else {
					this.getSearchDefault();
				}
			},
			suggestClick(item) {
				this.search_val = item.keyword;
				this.goSearchDetail();
			},
			goSearchDetail() {
				if (!this.search_val) return;
				const url = `/pages/search_detail/search_detail?keywords=${this.search_val}`;
				this.$navigateTo(url);
				this.search_val = '';
			}
		}
	}
</script>
<style>
	page {
		background-color: rgba(217, 217, 217, .1);
		height: 100vh;
	}
</style>
<style lang="scss">
	.ipt-box {
		display: flex;
		width: 95%;
		margin: 20rpx auto;

		.ipt {
			width: 85%;
			height: 70rpx;
			line-height: 70rpx;
			padding: 0 40rpx;
			border-radius: 40rpx;
			background-color: rgba(217, 217, 217, .3);
			font-size: 28rpx;
		}

		.search-btn {
			width: 15%;
			height: 60rpx;
			margin: auto 0;
			margin-left: 20rpx;
			line-height: 60rpx;
			background-color: rgba(255, 123, 0, 0.7);
			color: rgba(255, 255, 255, 0.9);
			font-size: 28rpx;
			border-radius: 20rpx;
			text-align: center;
		}
	}

	.suggest {
		display: flex;
		flex-direction: column;
		width: 95%;
		margin: 20rpx auto;

		.list {
			margin: 20rpx;
			display: flex;
			color: #868686;

			image {
				width: 30rpx;
				height: 30rpx;
				margin: auto 0;
				margin-right: 20rpx;
			}
		}
	}
</style>
